import { RouteLocationNormalized } from 'vue-router';
// import { useUserStore } from '@/stores/userStore';
import { getCanvasId } from './canvasId.ts';
// import { computed } from 'vue';

export function isWeChatBrowser(): boolean {
    return /micromessenger/i.test(navigator.userAgent) && !/wxwork/i.test(navigator.userAgent);
}

function isWorkWechatBrowser(): boolean {
    return /wxwork/i.test(navigator.userAgent);
}


async function handleAuth(route: RouteLocationNormalized, type: string): Promise<void> {
    const omniUserUuid = route.query.omni_user_uuid as string | undefined;
    const identityValue = route.query[type] as string | undefined;
    console.log("route.query."+type+": "+identityValue)
    //const store = useUserStore();
    //const storeOmniUserUuid = computed(() => store.user?.omni_user_uuid);
    //const storeIdentityValue = computed(() => store.user?.identity_value);

    // const storageIdentityValue = localStorage.getItem('identity_value');
    const storageOmniUserUuid = localStorage.getItem('omni_user_uuid');
    if (identityValue) {
        if (omniUserUuid === storageOmniUserUuid) {
            return;
        }
        // const store = useUserStore();
        // store.setUser({
        //     omni_user_uuid: omniUserUuid ? omniUserUuid:"",
        //     identity_type: type,
        //     identity_value: identityValue
        // });
        localStorage.setItem('omni_user_uuid', omniUserUuid ? omniUserUuid:"");
        localStorage.setItem('identity_type', type);
        localStorage.setItem('identity_value', identityValue);
        return;
    } else if (storageOmniUserUuid) {
        return;
    }

    // 如果没有找到identityValue或缓存的值，执行重定向
    const customerUuid = route.params.customerUuid as string;
    const redirectUri = encodeURIComponent(window.location.href);
    const apiType =  (type === "work_userid") ? "work" : "wechat"
    window.location.href = `${process.env.VITE_APP_BASE_API}/${apiType}/${customerUuid}/auth?redirectUri=${redirectUri}`;
}

export async function wechatIdentity(route: RouteLocationNormalized): Promise<void> {
    if (isWorkWechatBrowser()) {
        console.log("企业微信浏览器");
        await handleAuth(route, 'work_userid');
    } else if (isWeChatBrowser()) {
        console.log("微信浏览器");
        await handleAuth(route, 'wechat_openid');
    } else {
        console.log("其他浏览器")
        // 示例用法
        await getCanvasId(route)
    }
}
